/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.saber.certificacao.beansjsf.conversores;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

/**
 *
 * @author gbvbahia
 */
@FacesConverter(value = "urlConversor")
public class URLConversor implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value == null || value.equals("")) {
            return value;
        }
        if (value.trim().startsWith("http:\\\\")) {
            value = value.replace("http:\\\\", "http://");
        }else if(value.trim().startsWith("https:\\\\")){
            value = value.replace("https:\\\\", "https://");
        }
        if (value.trim().startsWith("http://")) {
            return value;
        } else if(value.trim().startsWith("https://")){
            return value;
        }
        else {
            return "http://" + value.trim();
        }
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value != null) {
            if (value.toString().trim().startsWith("http://") || value.toString().trim().startsWith("https://")) {
                return value.toString();
            } else {
                return "http://" + value.toString();
            }
        } else {
            return null;
        }
    }
}
